<template>
  <div class="user-container">
    <h1>用户列表</h1>

    <!-- 显示加载提示 -->
    <p v-if="loading">加载中...</p>

    <!-- 显示错误信息 -->
    <p v-if="errors" class="error">{{ errors }}</p>

    <!-- 用户列表 -->
    <ul v-if="!loading && !errors">
      <li v-for="user in users" :key="user.id">
        <p><strong>ID:</strong> {{ user.id }}</p>
        <p><strong>姓名:</strong> {{ user.name }}</p>
        <p><strong>Email:</strong> {{ user.email }}</p>
      </li>
    </ul>

    <!-- 刷新按钮 -->
    <button @click="fetchUsers">刷新用户列表</button>
  </div>
</template>

<script setup lang="ts">
import axios from 'axios'
import { ref } from 'vue'
const loading = ref(false)
const errors = ref()
const users = ref()
const fetchUsers = async () => {
  loading.value = !loading.value
  errors.value = ''
  try {
    const response = await axios.get('https://jsonplaceholder.typicode.com/users')
    users.value = response.data
  } catch (error) {
    errors.value = '请求失败'
  } finally {
    loading.value = !loading.value
  }
}
</script>

<style lang="scss" scoped>
.user-container {
  width: 400px;
  margin: 0 auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 5px;
  background-color: #f9f9f9;
}

ul {
  list-style: none;
  padding: 0;
}

li {
  margin-bottom: 15px;
  padding: 10px;
  border-bottom: 1px solid #ddd;
}

button {
  background-color: #007bff;
  color: white;
  border: none;
  padding: 5px 10px;
  cursor: pointer;
  border-radius: 3px;
}

button:hover {
  background-color: #0056b3;
}

.error {
  color: red;
  font-weight: bold;
}
</style>
